/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */

package org.jaxson.struts.encoder;


import java.io.Serializable;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaxson.struts.charts.AbstractChart;
import org.jaxson.struts.charts.AbstractChartRenderer;
import org.jaxson.struts.charts.annotations.ChartAnnotationReader;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.entity.StandardEntityCollection;

/**
 * Encodes a Model to a Chart using JFreeChart.
 * 
 * @author Joe Maisel
 */
public class JpegEncoder extends ResponseEncoder
{
	private String imageMap;
	private AbstractChart chart;

	private static final Log lager = LogFactory.getLog( JpegEncoder.class.getName() );
	
	@Override
	@SuppressWarnings("unchecked")
	public void encode( Serializable data ) throws EncodingException
	{
		lager.debug( "encoding " + data );
		
		try
		{
//			if( !(data instanceof Collection ) )
//			throw new IllegalArgumentException( "Charts can only be rendered with the Model is a collection" );
		
			// parse the data
			ChartAnnotationReader reader = new ChartAnnotationReader();
			reader.setLocale( getLocale() );
	
			// create the chart
			AbstractChartRenderer renderer = chart.getRenderer();
			
			if( chart.getDataset() == null )
				chart.setDataset( reader.read( (Collection)data, chart.datatype() ) );
			
			chart.setJFreeChart( renderer.render( chart.getDataset(), chart.getFormat() ) );
			
			if( renderer.getPlotHandler() != null )
				renderer.getPlotHandler().handle( chart.getJFreeChart().getPlot() );
			
			// create the image map
			ChartRenderingInfo info = new ChartRenderingInfo( new StandardEntityCollection() );
			ChartUtilities.writeChartAsJPEG( getOutputStream(), 1.0f, chart.getJFreeChart(), chart.getFormat().getWidth(), chart.getFormat().getHeight(), info );
			imageMap = ChartUtilities.getImageMap( chart.getFormat().getImageMapId(), info );
			lager.debug( imageMap );

		}
		catch( Exception e1 )
		{
			e1.printStackTrace();
			new EncodingException( e1 );
		}
	}
	
	/**
	 * @param chart the chart to set
	 */
	public void setChart( AbstractChart chart )
	{
		this.chart = chart;
	}

	/**
	 * Get the chart object
	 */
	public AbstractChart getChart()
	{
		return chart;
	}

	/**
	 * @return the imageMap
	 */
	public String getImageMap()
	{
		return imageMap;
	}
}
